package org.hj.modules.controller;



import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;

import org.apache.shiro.SecurityUtils;
import org.hj.common.annotation.AutoLog;
import org.hj.common.api.vo.Result;
import org.hj.common.system.query.QueryGenerator;
import org.hj.common.system.util.Excel.ExportParams;
import org.hj.common.system.util.Excel.HjEntityExcelView;
import org.hj.common.system.util.Excel.NormalExcelConstants;
import org.hj.common.system.vo.LoginUser;
import org.hj.common.util.oConvertUtils;
import org.hj.modules.AcStartController;
import org.hj.modules.entity.ActeLeave;
import org.hj.modules.entity.ActeLeaveApplication;
import org.hj.modules.service.IActeLeaveService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


@Slf4j
@Api(tags="出差申请")
@RestController
@RequestMapping("/acteLeave")
public class ActeLeaveController  extends AcStartController {
	@Autowired
	private IActeLeaveService acteLeaveService;
	
	/**
	  * 分页列表查询
	 * @param acteLeave
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "出差申请-分页列表查询")
	@ApiOperation(value="出差申请-分页列表查询", notes="出差申请-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ActeLeave>> queryPageList(ActeLeave acteLeave,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<ActeLeave>> result = new Result<IPage<ActeLeave>>();
		QueryWrapper<ActeLeave> queryWrapper = QueryGenerator.initQueryWrapper(acteLeave, req.getParameterMap());
		Page<ActeLeave> page = new Page<ActeLeave>(pageNo, pageSize);
		IPage<ActeLeave> pageList = acteLeaveService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param acteLeave
	 * @return
	 */
	@AutoLog(value = "出差申请-添加")
	@ApiOperation(value="出差申请-添加", notes="出差申请-添加")
	@PostMapping(value = "/add")
	public Result<ActeLeave> add(@RequestBody ActeLeave acteLeave) {
		Result<ActeLeave> result = new Result<ActeLeave>();
		try {
			acteLeaveService.save(acteLeave);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	@RequestMapping(value = "/submit")
	@ResponseBody
	public Object submit(@RequestParam(name = "id", required = true) String id) {
		String taskId=null;
		String ProId=null;
		Result<ActeLeave> result = new Result<ActeLeave>();
		// 获取当前登录人信息
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// 通过id抓取出差的信息
		ActeLeave  ActeLeave = acteLeaveService.getById(id);

		if (AppStatus.contains(ActeLeave.getAppstatus())) {
			return result.error500("待处理中,不能重复提交");
		}

		try {
			/** 工作流的操作 **/
			Map<String, Object> map = new LinkedHashMap<String, Object>();
			map.put("id", ActeLeave.getId()); // 
			map.put("申请人", ActeLeave.getCreateName()); // 当前用户的姓名
			map.put("所属部门", GetDeparmentText(ActeLeave.getSysOrgCode()));
			map.put("单证类型", GetDicDocumentText(ActeLeave.getType()));
			map.put("出差事项", ActeLeave.getReason());
			map.put("出差开始时间", ActeLeave.getBeginDate());
			map.put("出差结束时间", ActeLeave.getEndDate());
			map.put("是否加急", GetDicStatus_enText(ActeLeave.getDispatch()));
			map.put("申请时间", ActeLeave.getCreateTime());
			map.put("username", sysUser.getUsername()); // 指派代理人为当前用户
			
			if (ActeLeave.getAppstatus().equals("1"))
			{
				ProId=startProcessInstanceByKeyHasVariables("acteLeave", map); // 启动流程实例(请假单流程)通过KEY
				ActeLeave.setProcInstId(ProId);
			}
			else
			{
				ProId=ActeLeave.getProcInstId();
			}
			//根据ProId 查询任务ID_
			Map<Object, Object> taskMap=getActRuTaskById(ProId);
			if (null==taskMap) return result.error500("未找到流程任务编号");
		    taskId=taskMap.get("ID_").toString();
						
			//提交申请
		    Map<String, Object> submitMap =new LinkedHashMap<String, Object>();
		    submitMap.put("单证申请", "【已提交】");		//审批结果
			setVariablesByTaskIdAsMap(taskId,submitMap);			//设置流程变量
			setVariablesByTaskId(taskId,"RESULT","批准");
			completeMyPersonalTask(taskId);
			ActeLeave.setAppstatus("2");
			acteLeaveService.updateById(ActeLeave); // 记录存入数据库
			// zmap.put("ASSIGNEE_",sysUser.getUsername()); 用于给待办人发送新任务消息
			result.success("操作成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}
	
	
	/**
	  *  编辑
	 * @param acteLeave
	 * @return
	 */
	@AutoLog(value = "出差申请-编辑")
	@ApiOperation(value="出差申请-编辑", notes="出差申请-编辑")
	@PutMapping(value = "/edit")
	public Result<ActeLeave> edit(@RequestBody ActeLeave acteLeave) {
		Result<ActeLeave> result = new Result<ActeLeave>();
		ActeLeave acteLeaveEntity = acteLeaveService.getById(acteLeave.getId());
		if(acteLeaveEntity==null) {
			result.error500("未找到数据");
		}else {
			if (AppStatus.contains(acteLeaveEntity.getAppstatus())) {
				return result.error500("待处理中,不能重复提交");
			}
			boolean ok = acteLeaveService.updateById(acteLeave);
			//TODO 返回false说明什么？
			if(ok) {if (AppStatus.contains(acteLeaveEntity.getAppstatus())) {
				return result.error500("待处理中,不能重复提交");
			}
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出差申请-通过id删除")
	@ApiOperation(value="出差申请-通过id删除", notes="出差申请-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<ActeLeave> delete(@RequestParam(name="id",required=true) String id) {
		Result<ActeLeave> result = new Result<ActeLeave>();
		ActeLeave acteLeave = acteLeaveService.getById(id);
		if(acteLeave==null) {
			result.error500("未找到数据");
		}else {
			if (AppStatus.contains(acteLeave.getAppstatus())) {
				return result.error500("待处理中,不能重复提交");
			}
			boolean ok = acteLeaveService.removeById(id);
			if(ok) {
				result.success("删除成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "出差申请-批量删除")
	@ApiOperation(value="出差申请-批量删除", notes="出差申请-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<ActeLeave> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<ActeLeave> result = new Result<ActeLeave>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.acteLeaveService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出差申请-通过id查询")
	@ApiOperation(value="出差申请-通过id查询", notes="出差申请-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ActeLeave> queryById(@RequestParam(name="id",required=true) String id) {
		Result<ActeLeave> result = new Result<ActeLeave>();
		ActeLeave acteLeave = acteLeaveService.getById(id);
		if(acteLeave==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(acteLeave);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<ActeLeave> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              ActeLeave acteLeave = JSON.parseObject(deString, ActeLeave.class);
              queryWrapper = QueryGenerator.initQueryWrapper(acteLeave, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new HjEntityExcelView());
      List<ActeLeave> pageList = acteLeaveService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "出差申请列表");
      mv.addObject(NormalExcelConstants.CLASS, ActeLeave.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出差申请列表数据", "导出人:hj", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ActeLeave> listActeLeaves = ExcelImportUtil.importExcel(file.getInputStream(), ActeLeave.class, params);
              for (ActeLeave acteLeaveExcel : listActeLeaves) {
                  acteLeaveService.save(acteLeaveExcel);
              }
              return Result.ok("文件导入成功！数据行数:" + listActeLeaves.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
